const moment = require('moment')
const WebSocket = require('ws')
const pako = require('pako')
const log4js = require('log4js')
const config = require('../config/index')
const Redis = require('ioredis')
const redis = new Redis(config.redis)

// 配置log4js
log4js.configure(config.log4js)
const logger = log4js.getLogger('火币Pro主流币监控')

const wsUrl = 'wss://api.huobi.pro/ws'
const symbols = ['btcusdt', 'bchusdt', 'ethusdt', 'etcusdt', 'eosusdt', 'ltcusdt']
let recordList = {}

initWs()

/**
 * 初始化websocket
 */
function initWs () {
  let ws = new WebSocket(wsUrl)
  let pingTimer = null
  let reTimer = null
  ws.on('open', () => {
    console.log('open')
    subscribe(ws)
    ws.isAlive = true
    // 每10秒ping一次
    pingTimer = setInterval(() => {
      if (ws.isAlive === false) {
        clearInterval(pingTimer)
        return ws.terminate()
      }
      ws.isAlive = false
      heartbeat()
    }, 10000)
  })
  ws.on('message', (data) => {
    let text = pako.inflate(data, {
      to: 'string'
    })
    let msg = JSON.parse(text)
    if (msg.ping) {
      ws.send(JSON.stringify({
        pong: msg.ping
      }))
    } else if (msg.pong) {
      ws.isAlive = true
    } else if (msg.tick) {
      handle(msg)
    } else {
      console.log(text)
    }
  })

  ws.on('close', () => {
    console.log('close')
    clearInterval(pingTimer)
    clearTimeout(reTimer)
    reTimer = setTimeout(() => {
      initWs()
    }, 2000)
  })

  ws.on('error', err => {
    console.log('error', err)
    logger.error(err)
    clearInterval(pingTimer)
    clearTimeout(reTimer)
    reTimer = setTimeout(() => {
      initWs()
    }, 2000)
  })

  function heartbeat () {
    let ping = Date.now()
    ws.send(JSON.stringify({
      ping: ping
    }))
  }
}

function handle (data) {
  let symbol = data.ch.split('.')[1]
  let channel = data.ch.split('.')[2]
  if (channel === 'kline') {
    // 开盘价
    let open = data.tick.open
    // 收盘价
    let close = data.tick.close
    // 涨跌幅
    let percent = parseFloat(((close - open) / open * 100).toFixed(2))
    // 处理初始化后没有记录
    if (!recordList[symbol]) {
      recordList[symbol] = {}
    }
    let record = recordList[symbol]
    // 初始化新记录
    if (!record.tick || record.tick.id !== data.tick.id) {
      record.tick = data.tick
      record.percent = 0
    }
    let now = moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
    // 如果是阳线
    if (percent > 0 && record.percent >= 0) {
      if (record.percent === 0) {
        if (symbol === 'btcusdt') {
          record.percent = 0.5
        } else {
          record.percent = 1
        }
      }
      if (percent > record.percent) {
        record.percent = (parseInt(percent / 0.5) + 1) * 0.5
        console.log(`币种：${symbol}, 涨幅：${percent}, 时间：${now}`)
        redis.publish('news', JSON.stringify({
          type: 2,
          source: '火币Pro',
          symbol: symbol.toUpperCase(),
          time: now,
          percent: percent,
          content: `${symbol.toUpperCase()}5分钟内涨幅：${percent}% \n当前价格$${close}`
        }))
      }
    } else if (percent < 0 && record.percent <= 0) {
      if (record.percent === 0) {
        if (symbol === 'btcusdt') {
          record.percent = -0.5
        } else {
          record.percent = -1
        }
      }
      if (percent < record.percent) {
        record.percent = (parseInt(percent / 0.5) - 1) * 0.5
        console.log(`币种：${symbol}, 跌幅：${percent}, 时间：${now}`)
        redis.publish('news', JSON.stringify({
          type: 2,
          source: '火币Pro',
          percent: percent,
          content: `${symbol.toUpperCase()}5分钟内跌幅：${percent}% \n当前价格$${close}`,
          symbol: symbol,
          time: now
        }))
      }
    } else {
      record.percent = 0
    }
  }
}

/**
 * 订阅K线
 * @param ws
 */
function subscribe (ws) {
  for (let symbol of symbols) {
    ws.send(JSON.stringify({
      'sub': `market.${symbol}.kline.5min`,
      'id': `${symbol}`
    }))
  }
}
